#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#define STACK_SIZE 2048
// 事件类型定义
#define EVENT_ONE 0x00000001
#define EVENT_TWO 0x00000002

osEventFlagsId_t g_eventId;

/* 事件等待任务函数 */
void TaskEventWait( void *arg ){
    uint32_t event;

    printf("[EventWait] Start\r\n");
    event = osEventFlagsWait(g_eventId, 
      EVENT_ONE | EVENT_TWO, osFlagsWaitAny | osFlagsNoClear, osWaitForever);

    printf("[EventWait] Read Any Event :0x%x\r\n", event);

    event = osEventFlagsWait(g_eventId, 
      EVENT_ONE | EVENT_TWO, osFlagsWaitAll, osWaitForever);
    printf("[EventWait] Read All Event :0x%x\r\n", event);

    osEventFlagsDelete( g_eventId );
}

/* 事件设置任务函数 */
void TaskEventSet( void ){
    printf("[EventSet] Start \r\n");

    osEventFlagsSet(g_eventId, EVENT_ONE);
    printf("[EventSet] EVENT_ONE Set OK \r\n");

    osDelay(100);

    osEventFlagsSet(g_eventId, EVENT_TWO);
    printf("[EventSet] EVENT_TWO Set OK \r\n");
}

void EventDemoMain(int *arg){
    osThreadAttr_t attr;

    g_eventId = osEventFlagsNew( NULL );

    // 先锁定任务调度，防止新创建的任务比本任务高而发生调度
    osKernelLock();

    attr.name = "TaskEventWait";
    attr.attr_bits  = 0U;
    attr.cb_mem     = NULL;
    attr.cb_size    = 0U;
    attr.stack_mem  = NULL;
    attr.stack_size = STACK_SIZE;
    attr.priority   = osPriorityNormal;
    if (osThreadNew((osThreadFunc_t)TaskEventWait, NULL, &attr) == NULL) {
        printf("[Main] Create TaskEventWait Failed\r\n");
        return;
    }

    printf("[Main] Create TaskEventWait OK\r\n");

    attr.name = "TaskEventSet";
    attr.attr_bits  = 0U;
    attr.cb_mem     = NULL;
    attr.cb_size    = 0U;
    attr.stack_mem  = NULL;
    attr.stack_size = STACK_SIZE;
    attr.priority   = osPriorityNormal;
    if (osThreadNew((osThreadFunc_t)TaskEventSet, NULL, &attr) == NULL) {
        printf("[Main] Create TaskEventset\r\n");
        return;
    }

    printf("[Main] Create TaskEventSet OK\r\n");

    // 解锁任务调度，此时会发生任务调度，执行就绪队列中最高优先级任务
    osKernelUnlock();
}

SYS_RUN( EventDemoMain );

